// Copyright 2020 morgine.com. All rights reserved.

package handlers

import (
	"gitee.com/tugoer/psys/container"
	"gitee.com/tugoer/psys/models"
	"gitee.com/tugoer/psys/services"
	"github.com/gin-gonic/gin"
)

func GetSliders(ctx *gin.Context) {
	sliders, err := container.Sliders.Get()
	if err != nil {
		ctx.Error(err)
	} else {
		err = InitSliderImageUrl(sliders)
		if err != nil {
			ctx.Error(err)
		} else {
			ctx.JSON(200, gin.H{"sliders": sliders})
		}
	}
}

type saveSlidersParam struct {
	JsonBody string `required:"" desc:"序列化后的 JSON 字符串"`
}

func UpdateSliders(ctx *gin.Context) {
	p := &saveSlidersParam{}
	if err := ctx.Bind(p); err != nil {
		ctx.AbortWithError(500, err)
	} else {
		err := container.Sliders.Save(p.JsonBody)
		if err != nil {
			ctx.JSON(200, NewMessage("warning", err.Error()))
		} else {
			ctx.JSON(200, NewMessage("success", "已保存"))
		}
	}
}

func InitSliderImageUrl(sliders []*models.Slider) error {
	var err error
	for _, s := range sliders {
		s.ImgUrl, err = services.ImgStore.GetServeUrl(s.Img)
		if err != nil {
			return err
		}
	}
	return nil
}
